package app.domain.orderBook;

import java.util.HashMap;
import java.util.Map;

import app.domain.order.Order;
import app.domain.order.util.Ticket;

public class OrderBookMap {

	private Map<Ticket,OrderBook> orderBookMap = new HashMap<>();

	public void put(Ticket ticket, OrderBook orderBook) {
		orderBookMap.put(ticket, orderBook);
	}

	public OrderBook get(Ticket ticket) {
		return orderBookMap.get(ticket);
	}
	
	public void putOrder(Order order) {
		OrderBook orderBook = orderBookMap.get(order.getTicket());
		orderBook.add(order);
		orderBookMap.put(order.getTicket(), orderBook);
	}

	public OrderBook remove(Ticket ticket) {
		return orderBookMap.remove(ticket);
	}
	
	public boolean removeOrder(Order order) {
		for(Ticket ticket : Ticket.values()) {
			for(Order other : orderBookMap.get(ticket).getList()) {
				if(order.getReferenceId() == other.getReferenceId()) {
					OrderBook orderBook = orderBookMap.remove(ticket);
					orderBook.remove(other);
					orderBookMap.put(ticket, orderBook);
					return true;
				}
			}
		}
		return false;
	}
	
	public void deleteClientOrders(String clientId) {
		for(Ticket ticket : Ticket.values()) {
			OrderBook orderBook = orderBookMap.remove(ticket);
			for (int i = 0; i < orderBook.size(); i++) {
				if(clientId.equals(orderBook.get(i).getClientId())) {
					orderBook.remove(i);
					i--;
				}
			}
			orderBookMap.put(ticket,orderBook);
		}
	}
}
